<?php

namespace App\Console;

use App\Jobs\ManagerDuty;
use App\Jobs\RongcloudHistory;
use App\Models\AccountLog;
use App\Models\HouseDistrict;
use App\Models\ShopGoods;
use App\Models\ShopGroupGoods;
use App\Models\ShopOrder;
use App\Models\ShopOrderAppraise;
use App\Models\ShopOrderLog;
use App\Models\ShopRefundLog;
use App\Models\ShopStore;
use App\Models\ShopRefund;
use App\Models\LogStoreView;
use App\Models\LogStoreStatistics;
use App\Models\ShopOrderSplit;
use App\Models\Account;
use App\Models\ShopSeckillGoods;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Models\Config;
use Prophecy\Exception\InvalidArgumentException;
use Symfony\Component\CssSelector\Exception\InternalErrorException;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
	 * 		* * * * * php /usr/share/nginx/huicheng_api/artisan schedule:run >> /dev/null 2>&1
	 *
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
		// 每小时执行，获取融云聊天历史记录并插入表
		$schedule->job((new RongcloudHistory())->onQueue('rongcloud'))->hourly();
		
		// 监听管理人员值班状态，值班时间每分钟递增
		$schedule->job((new ManagerDuty())->onQueue('rongcloud'))->dailyAt('00:05');
		
		// 每天凌晨3点更新房屋数据缓存
		$schedule->call(function(){
			Cache::forget('HouseDistrict_treeChildren_0id,name');
			HouseDistrict::treeChildren(0,'id,name');
			Cache::forget('HouseDistrict_treeChildrenOne_0id');
			$data = HouseDistrict::treeChildrenOne(0,'id');
			$data->each(function($v,$k){
				Cache::forget('HouseDistrict_treeChildren_'.$v->id.'id,name');
				HouseDistrict::treeChildren($v->id,'id,name');
				Cache::forget('HouseDistrict_treeChildrenOne_'.$v->id.'id');
				HouseDistrict::treeChildrenOne($v->id,'id');
			});
		})->dailyAt('03:00');

		//秒杀订单超时无效退款,每分钟查询
		$schedule->call(function(){
            $seckill_time =  Config::key('order_seckill_deadline')->value('value');
            $seckill_end_time = date('Y-m-d H:i:s',(time() - $seckill_time));

            ShopOrder::select(['uid','created_at','status','uid','order_sn'])
                ->where(['status'=>1,'order_type'=>1])
                ->where('created_at','<',$seckill_end_time)
                ->get()->each(function($v,$k){
                    DB::transaction(function () use ($v) {
                        $return = ShopOrder::where(['order_sn' => $v->order_sn])->update(['status' => 7]);
                        //插入日志
                        ShopOrderLog::createOrderLog($v->uid, $v->order_sn, '订单超时未支付,自动取消', 'system');
                        //回滚库存
                        ShopOrder::rbackGoodsStock($v->order_sn);
                        return $return;
                    });
                });
        })->everyMinute();

        //其它订单超时无效,每分钟查询
        $schedule->call(function(){

            $order_time =  Config::key('order_deadline')->value('value');
            $order_end_time = date('Y-m-d H:i:s',(time() - $order_time));

            ShopOrder::select(['uid','created_at','status','uid','order_sn'])
                ->where(['status'=>1])
                ->where('order_type','<>',1)
                ->where('order_type','<>',4)
                ->where('created_at','<',$order_end_time)
                ->get()
                ->each(function($v,$k){
                    DB::transaction(function () use ($v) {

                        ShopOrder::where(['order_sn' => $v->order_sn])->update(['status' => 7]);
                        //插入日志
                        ShopOrderLog::createOrderLog($v->uid, $v->order_sn, '订单超时未支付,自动取消', 'system');
                        //回滚库存
                        ShopOrder::rbackGoodsStock($v->order_sn);
                    });
                });
        })->everyMinute();
        //秒杀结束关闭商品
        $schedule->call(function(){
            ShopSeckillGoods::where(['status'=>2,'stock'=>0])->update(['status'=>3]);
            ShopSeckillGoods::where(['status'=>2])->where(['end_time'<date('Y-m-d H:i:s')])->update(['status'=>3]);
            ShopGroupGoods::where(['status'=>2])->where(['end_time'<date('Y-m-d H:i:s')])->update(['status'=>3]);

        })->dailyAt('03:00');
        //拼团超时无效，自动退款
        $schedule->call(function(){
            ShopGroupGoods::where(['status'=>2])->where(['end_time'<date('Y-m-d H:i:s')])->get()->each(function($v,$k){
                DB::transaction(function () use ($v) {
                    $create = ShopGroupGoods::where(['id'=>$v->id])->update(['status'=>3]);
                    if (!$create) {
                        throw new \Exception('插入退款表失败');
                    }

                    ShopOrderGoods::where(['goods_id'=>$v->id,'goods_type'=>2])->get()->each(function($goods_info,$k){
                       $refund_sn = ShopOrder::createOrderSN();
                       $refund_info = array(
                           'order_sn'=>$goods_info->order_sn,
                           'refund_sn'=>$refund_sn,
                           'goods_id'=>'',
                           'reason'=>'拼团失败，因人数不够，系统自动退款',
                           'detail'=>'拼团失败，因人数不够，系统自动退款',
                           'refund_reply'=>'拼团失败，因人数不够，系统自动退款',
                           'goods_amount'=>0,
                           'status'=>1,
                           'store_id'=>$goods_info->store_id,
                           'order_amount'=>$goods_info->goods_price,
                           'refund_amount'=>$goods_info->goods_price,
                           'reason_id'=>0,
                           'uid'=>$goods_info->uid,
                           'refund_type'=>1,
                           'created_at'=>date('Y-m-d H:i:s'),
                           'updated_at'=>date('Y-m-d H:i:s'),
                       );
                       $create = ShopRefund::insert($refund_info);
                       if (!$create) {
                           throw new \Exception('插入退款表失败');
                       }
                       $update = ShopOrder::where(['order_sn' => $refund_info['order_sn']])->update(['status' => 7]);
                       if (!$update) {
                           throw new \Exception('更改订单状态失败');
                       }
                       //插入申请退款记录
                       $details = '拼团失败，因人数不够，系统自动退款';
                       $create = ShopOrderLog::createOrderLog($goods_info->uid , $refund_info['order_sn'], $details, $goods_info->uid, 2);
                       if (!$create) {
                           throw new \Exception('插入订单日志失败');
                       }
                       $create = ShopRefundLog::createOrderLog($goods_info->uid, $refund_info['refund_sn'], $details, $goods_info->uid, 1);
                       if (!$create) {
                           throw new \Exception('插入退款日志失败');
                       }
                       //调用退款接口
                       ShopRefund::AppRefund($refund_info);
                   });
                });
            });

        })->dailyAt('03:00');
        //统计日志操作
        $schedule->call(function(){
            ShopStore::where(['status'=>1,'is_del'=>0])->select('id')->get()->each(function($v,$k){
                DB::transaction(function () use ($v) {
                    $store_id=$v->id;
                    $time = date("Y-m-d",strtotime("-1 day"));
                    $insert = array();
                    $insert['day'] = $time;
                    $insert['view_num'] = LogStoreView::where(['store_id'=>$store_id,'date'=>$time])->count();
                    $insert['order_num'] = ShopOrder::where(['store_id'=>$store_id])
                        ->where('created_at','>=',$time.' 00:00:00')
                        ->where('created_at','<=',$time.' 23:59:59')
                        ->count();
                    $insert['amount_num'] = ShopOrderSplit::where(['store_id'=>$store_id,'status'=>2])
                        ->where('updated_at','>=',$time.' 00:00:00')
                        ->where('updated_at','<=',$time.' 23:59:59')
                        ->sum('store_amount');
                    $return['score_num'] = $v->score;
                    $insert['store_id'] = $store_id;
                    LogStoreStatistics::create($insert);
                    $sale_number = ShopOrder::where(['status'=>2,'store_id'=>$store_id])->whereRaw('DateDiff(created_at,current_timestamp())<=30')->count();
                    ShopStore::where(['store_id'=>$store_id])->update('sale_number',$sale_number);
                });
            });

        })->dailyAt('00:50');
        //订单确认收货
        $schedule->call(function(){
            $order_time =  Config::key('order_confirm_time')->value('value');
            ShopOrder::where(['status'=>3])->where('updated_at','<',date('Y-m-d H:i:s',time()-$order_time*3600*24))->get()
                ->each(function($v,$k){
                    ShopOrder::confirmOrder($v->order_sn,$v->uid,2);
                });
        })->everyMinute();
        //商品定时上下架
        $schedule->call(function(){
            //上架：
            $time=date('Y-m-d H:i:s');
            ShopGoods::where(['start_type'=>2,'status'=>1])->where('start_time','<',$time)->get()->each(function($v,$k) use($time){
                //判断库存
                if($v->stock>0){
                    //判断时间
                    if($v->end_type==2 && $v->end_time>$time){
                        ShopGoods::where('id',$v->id)->update(['status'=>1]);
                    }
                }
            });
            //下架:
            ShopGoods::where(['end_type'=>2,'status'=>2])->where('end_time','<',$time)->update(['status'=>2]);
        })->everyMinute();
        
        //订单分成
        $schedule->call(function(){
            ShopOrderSplit::where(['status'=>1])->where('confirm_at','<=',date('Y-m-d',strtotime("-1 day")).' 00:00:00')->get()->each(function($v,$k){
                DB::transaction(function () use ($v) {
                    $store_amount = $v->store_amount;
                    $store_uid = ShopStore::where(['id'=>$v->store_id])->value('uid');
                    Account::where(['uid'=>$store_uid])->increment('amount',$store_amount);
                    AccountLog::insertAccountLog($store_uid,$v->store_amount,'order',$v->order_sn);
                    //计算分成
                    if($v->terrace_amount>0){
                        Account::where(['uid'=>$v->split_uid])->increment('amount',$v->terrace_amount);
                        AccountLog::insertAccountLog($v->split_uid,$v->terrace_amount,'order',$v->order_sn);
                    }
                    if($v->platform_amount>0){
                        Account::where(['uid'=>1])->increment('amount',$v->platform_amount);
                        AccountLog::insertAccountLog(1,$v->platform_amount,'order',$v->order_sn);
                    }
                });
                ShopOrderSplit::where(['id'=>$v->id])->update(['status'=>2]);
            });

        })->everyMinute();
            //->dailyAt('00:10');

    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}
